/**
 * @author SaoE
 * @date 2025/3/25 15:22
 */
public class _142 {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow){
                break;
            }
        }
        if (fast == null || fast.next == null){
            return null;
        }
        int count = 0;
        while(fast != slow){
            fast = fast.next.next;
            slow = slow.next;
            count++;
        }
        fast = head;
        while (count > 0){
            fast = fast.next;
            count--;
        }
        slow = head;
        while (fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
